import { defineStore } from 'pinia';

// tab选项卡
interface TabItem {
	path: string;
	name: string;
	title: string;
	active: boolean;
}
export const useTabs = defineStore('tabs', {
	state: () => ({
		tabs: [] as any,
	}),
	actions: {
		setTabs(route: any) {
			if (['403', '404', 'login'].includes(route.name)) return
			// 判断路由是否存在，如果存在则不添加
			this.tabs.map((item: TabItem) => { item.active = false; return item; })
			const isExist = this.tabs.some((item: TabItem) => item.path === route.path);
			if (!isExist) {
			    this.tabs.push({
					path: route.path,
					name: route.name,
					title: route.meta.title,
					active: true,
				});
				if (this.tabs.length > 10) this.tabs.shift();
			} else {
			    this.tabs.map((item: TabItem) => {
					if (item.path === route.path) {
						item.active = true;
					}
				})
			}
			// console.log('this.tabs', this.tabs);
		},
		changeTabs({ item: _item, router } : any) {
			this.tabs.map((item: TabItem) => { item.active = false; return item; })
			this.tabs.map((item: TabItem) => {
				if (item.path === _item.path) {
					item.active = true;
				}
			})
			router.push(_item.path);
		},
		removeTabs({ item: _item, index, router }: any) {
			const isNext = this.tabs[index + 1]?.path;
			if (isNext) {
				this.tabs[index + 1].active = true;
				router.push(isNext);
			} else {
				this.tabs[index - 1].active = true;
				router.push(this.tabs[index - 1].path);
			}
			this.tabs = this.tabs.filter((tab: any) => tab.path !== _item.path);
		}
	},
});
